package org.tobuy.dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.tobuy.vo.*;
import org.tobuy.dao.IDealDAO;

public class DealDAOImpl implements IDealDAO{
	
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	ResultSet rs = null;
	public DealDAOImpl(Connection conn){
		this.conn = conn;
	}

	public boolean addDeal(Deal deal) throws Exception {
		boolean flag = false;
		String sql = "INSERT INTO deal(dealid,buyerid,sellerid,itemid,dealprice,dealdate) VALUES(?,?,?,?,?,?)";
		this.pstmt = this.conn.prepareStatement(sql);
		this.pstmt.setInt(1, deal.getDeal_id());
		this.pstmt.setString(2, deal.getBuyer_id());
		this.pstmt.setString(3, deal.getSeller_id());
		this.pstmt.setInt(4, deal.getItem_id());
		this.pstmt.setDouble(5, deal.getDeal_price());
		this.pstmt.setDate(6, new Date(System.currentTimeMillis()));
		if(pstmt.executeUpdate()!=0){
			flag = true;
		}
		this.pstmt.close();
		return flag;
	}

	public List<Deal> findBoughtDeal(User buyer) throws Exception {
		List<Deal> deals = new ArrayList<Deal>();
		String sql = "Select * from deal where buyerid=?";
		this.pstmt = this.conn.prepareStatement(sql);
		this.pstmt.setString(1, buyer.getUser_id());
		rs = this.pstmt.executeQuery();
		while(rs.next()){
			Deal deal = getDealFromRs(rs);
			deals.add(deal);
		}
		this.pstmt.close();
		return deals;
	}

	public List<Deal> findSoldDeal(User seller) throws Exception {
		List<Deal> deals = new ArrayList<Deal>();
		String sql = "Select * from deal where sellerid=?";
		this.pstmt = this.conn.prepareStatement(sql);
		this.pstmt.setString(1, seller.getUser_id());
		rs = this.pstmt.executeQuery();
		while(rs.next()){
			Deal deal = getDealFromRs(rs);
			deals.add(deal);
		}
		this.pstmt.close();
		return deals;
	}
	private Deal getDealFromRs(ResultSet rs){
		Deal deal = new Deal();
		try{
			deal.setDeal_id(rs.getInt("dealid"));
			deal.setBuyer_id(rs.getString("buyerid"));
			deal.setSeller_id(rs.getString("sellerid"));
			deal.setItem_id(rs.getInt("itemid"));
			deal.setDeal_price(rs.getDouble("dealprice"));
			deal.setDeal_date(rs.getTimestamp("dealdate"));
		}catch(SQLException e){
			e.printStackTrace();
		}
		return deal;
	}

}
